package org.rc.web;

import com.googlecode.objectify.Key;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rc.dao.AthleteDao;
import org.rc.dao.RaceDao;
import org.rc.model.Athlete;
import org.rc.model.Race;
import org.rc.model.Result;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

/**
 * Race servlet
 *
 */
public class CompareRaceServlet extends IndexServlet {

    private static final Logger LOGGER = LoggerFactory.getLogger(RaceServlet.class);
    private RaceDao raceDao = new RaceDao();
    private AthleteDao athleteDao = new AthleteDao();
    
    
    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String ids = request.getParameter("ids");
        List<Race> races = new ArrayList<Race>();
        for(String id : ids.split(",")) {
            races.add(raceDao.get(new Long(id)));
        }
        Map<Athlete, List<Result>> results = athleteDao.getResultsForCommonAthletesInAll(races);
        Collection<Athlete> athletes = results.keySet();
        Map<Long, Race> averageTimes = calcAverageTimes(results);
        StringBuilder sb = new StringBuilder();

        for(Long time : averageTimes.keySet()) {
            sb.append(averageTimes.get(time).getName()+averageTimes.get(time).getDate() + " " + time + "/n");
        }
        response.getWriter().write(athletes.size() + " competed in all races\n"+sb.toString());
    }

    /**
     * Calculate the average time per race for the results passed.
     * Returns an ordered Map by time.
     * @param results
     * @return 
     */
    private Map<Long, Race> calcAverageTimes(Map<Athlete, List<Result>> results) {
        Map<Long, Race> result = new TreeMap<Long,Race>();
        Map<Key<Race>,Long> allTimes = new HashMap<Key<Race>,Long>();
        for(Athlete a : results.keySet()) {
            for(Result r : results.get(a)) {
                Integer place = r.getPlace();
                r.getTimeInSeconds();
                if(!allTimes.containsKey(r.getRace())) {
                    allTimes.put(r.getRace(), new Long(r.getTimeInSeconds()));
                } else {
                    Long time = allTimes.get(r.getRace());
                    time = time + r.getTimeInSeconds();
                    allTimes.put(r.getRace(), time);
                }
                
            }
        }
        Map<Key<Race>, Race> races = raceDao.ofy().get(allTimes.keySet());
        for(Key<Race> kr : allTimes.keySet()) {
            result.put(allTimes.get(kr)/results.size(), races.get(kr));
        }
        return result;
    }
}
